<template>
  <div class="login">
    <div class="page-login--layer page-login--layer-area">
      <ul class="circles">
        <li v-for="n in 10" :key="n"></li>
      </ul>
    </div>
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
      <h3 class="title">后台管理系统</h3>
      <el-form-item prop="username">
        <el-input v-model="loginForm.username" type="text" auto-complete="off" placeholder="账号">
          <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon"/>
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input v-model="loginForm.password" type="password" auto-complete="off" placeholder="密码"
                  @keyup.enter.native="handleLogin">
          <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon"/>
        </el-input>
      </el-form-item>
      <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">记住密码</el-checkbox>
      <el-form-item style="width:100%;">
        <el-button type="primary" style="width:100%;" @click.native.prevent="handleLogin">
          <span>登 录</span>
        </el-button>
        <div style="float: right;" v-if="sysRegister">
          <router-link class="link-type" :to="'/register'">立即注册</router-link>
        </div>
      </el-form-item>
    </el-form>
    <div id="captcha-mask" v-show="showCaptchaMask">
      <div id="captcha-div"></div>
    </div>
    <!--  底部  -->
    <div class="el-login-footer">
      <span>Copyright © 2018-2024 zero-wsh.top All Rights Reserved.</span>
    </div>
  </div>
</template>

<script>
import {decrypt, encrypt} from '@/utils/jsencrypt';
import {setToken, setTokenKey} from "@/utils/auth";

export default {
  name: "Login",
  data() {
    return {
      codeUrl: "",
      loginForm: {
        username: "admin",
        password: "admin123",
        rememberMe: false
      },
      loginRules: {
        username: [
          {required: true, trigger: "blur", message: "请输入您的账号"}
        ],
        password: [
          {required: true, trigger: "blur", message: "请输入您的密码"}
        ],
        code: [{required: true, trigger: "change", message: "请输入验证码"}]
      },
      // 验证码开关
      sysCaptcha: true,
      // 注册开关
      sysRegister: false,
      // 行为验证码
      showCaptchaMask: false,
      redirect: undefined
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && decodeURIComponent(route.query.redirect);
      },
      immediate: true
    }
  },
  created() {
    this.getCookie();
    this.sysControl();
  },
  methods: {
    getCookie() {
      const username = localStorage.getItem("username");
      const password = localStorage.getItem("password");
      const rememberMe = localStorage.getItem('rememberMe')
      this.loginForm = {
        username: username === null ? this.loginForm.username : username,
        password: password === null ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === null ? false : Boolean(rememberMe)
      };
    },
    sysControl() {
      let config = {
        url: "/sysControl",
        method: 'get'
      }
      this.$axiosAuth(config).then(res => {
        this.sysCaptcha = res.data.sysCaptcha
        this.sysRegister = res.data.sysRegister
      }).finally(() => {
      });

    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          if (this.sysCaptcha) {
            //开启行为验证码
            this.behaviorVerificationCode(this.loginForm)
          } else {
            let loading = this.$loading({
              spinner: "el-icon-loading",
              text: "正在登录中",
              background: "rgba(0, 0, 0, 0.8)"
            });
            let config = {
              url: "/login",
              method: 'post',
              data: this.loginForm
            }
            this.$axiosAuth(config).then(res => {
              setToken(res.data.token)
              setTokenKey(res.data.tokenKey)
              // commit('SET_TOKEN', res.data.token)

              this.$router.push({path: this.redirect || "/"}).then(() => {
                this.$nextTick(() => {
                  loading.close()
                })
              });
            }).catch(() => {
              this.$nextTick(() => {
                loading.close()
              })
            });
          }
        }
      });
    },
    //行为验证码处理
    behaviorVerificationCode(loginForm) {
      this.showCaptchaMask = true
      const captchaConfig = {
        // 请求验证码接口
        requestCaptchaDataUrl: process.env.VUE_APP_BASE_API + process.env.VUE_APP_AUTH + "/genCaptcha",
        // 验证验证码接口
        validCaptchaUrl: process.env.VUE_APP_BASE_API + process.env.VUE_APP_AUTH + "/login",
        // 绑定的div
        bindEl: "#captcha-div",
        // 验证成功回调函数
        validSuccess: (res, c, t) => {
          // console.log("验证码验证成功回调...")
          this.showCaptchaMask = false
          // 销毁验证码
          t.destroyWindow();
          setToken(res.data.token)
          setTokenKey(res.data.tokenKey)
          // commit('SET_TOKEN', res.data.token)
          let loading = this.$loading({
            spinner: "el-icon-loading",
            text: "正在登录中",
            background: "rgba(0, 0, 0, 0.8)"
          });
          this.$router.push({path: this.redirect || "/"}).then(() => {
            loading.close()
          });
        },
        // 验证失败的回调函数(可忽略，如果不自定义 validFail 方法时，会使用默认的)
        validFail: (res, c, tac) => {
          if (res.code === 4001) {
            // 验证失败后重新拉取验证码
            tac.reloadCaptcha();
          } else {
            this.showCaptchaMask = false
            tac.destroyWindow();
            this.$message.error(res.msg)
          }
        },
        btnCloseFun: (el, tac) => {
          this.showCaptchaMask = false
          tac.destroyWindow();
        }
      }
      if (this.loginForm.rememberMe) {
        localStorage.setItem("username", this.loginForm.username);
        localStorage.setItem("password", encrypt(this.loginForm.password));
        localStorage.setItem('rememberMe', this.loginForm.rememberMe);
      } else {
        localStorage.removeItem("username");
        localStorage.removeItem("password");
        localStorage.removeItem('rememberMe');
      }
      window.initTAC("static/tac", captchaConfig).then(tac => {
        tac.config.insertRequestChain(0, {
          preRequest(type, requestParam) {
            if (type === "validCaptcha") {
              // console.log("请求前拦截", requestParam)
              let data = requestParam.data
              requestParam.data = Object.assign(data, loginForm)
              requestParam.data.data.startTime = requestParam.data.data.startTime.getTime()
              requestParam.data.data.stopTime = requestParam.data.data.stopTime.getTime()
            }
            return true;
          },
          postRequest(type, requestParam, res) {
            // console.log("请求后拦截", requestParam, res)
            return true;
          }
        })
        tac.init();
      })
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss">

#captcha-mask {
  display: flex;
  z-index: 99;
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.53);
  justify-content: center;
  align-items: center;
}

.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  //background-color: #f0f2f5;
  background-image: linear-gradient(to top, #a8edea 0%, #fed6e3 100%);
  background-size: cover;
}

.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
}

.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 25px 25px 5px 25px;

  .el-input {
    height: 38px;

    input {
      height: 38px;
    }
  }

  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}

.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.login-code {
  width: 33%;
  height: 38px;
  float: right;

  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}

.login-code-img {
  height: 38px;
}

// 背景
.circles {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
  margin: 0px;
  padding: 0px;

  li {
    position: absolute;
    display: block;
    list-style: none;
    width: 20px;
    height: 20px;
    background: #fff;
    animation: animate 25s linear infinite;
    bottom: -200px;

    @keyframes animate {
      0% {
        transform: translateY(0) rotate(0deg);
        opacity: 1;
        border-radius: 0;
      }

      100% {
        transform: translateY(-1000px) rotate(720deg);
        opacity: 0;
        border-radius: 50%;
      }
    }

    &:nth-child(1) {
      left: 15%;
      width: 80px;
      height: 80px;
      animation-delay: 0s;
    }

    &:nth-child(2) {
      left: 5%;
      width: 20px;
      height: 20px;
      animation-delay: 2s;
      animation-duration: 12s;
    }

    &:nth-child(3) {
      left: 70%;
      width: 20px;
      height: 20px;
      animation-delay: 4s;
    }

    &:nth-child(4) {
      left: 40%;
      width: 60px;
      height: 60px;
      animation-delay: 0s;
      animation-duration: 18s;
    }

    &:nth-child(5) {
      left: 65%;
      width: 20px;
      height: 20px;
      animation-delay: 0s;
    }

    &:nth-child(6) {
      left: 75%;
      width: 150px;
      height: 150px;
      animation-delay: 3s;
    }

    &:nth-child(7) {
      left: 35%;
      width: 200px;
      height: 200px;
      animation-delay: 7s;
    }

    &:nth-child(8) {
      left: 50%;
      width: 25px;
      height: 25px;
      animation-delay: 15s;
      animation-duration: 45s;
    }

    &:nth-child(9) {
      left: 20%;
      width: 15px;
      height: 15px;
      animation-delay: 2s;
      animation-duration: 35s;
    }

    &:nth-child(10) {
      left: 85%;
      width: 150px;
      height: 150px;
      animation-delay: 0s;
      animation-duration: 11s;
    }
  }
}

// 层
.page-login--layer {
  position: absolute;
  top: 0px;
  right: 0px;
  bottom: 0px;
  left: 0px;
  overflow: auto;
}

.page-login--layer-area {
  overflow: hidden;
}
</style>
